package cn.gong.movie.db;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import framework.database.annotaion.DBField;
import framework.manage.ManageApp;
import framework.utils.LogUtils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class AppSQLiteOpenHelper extends SQLiteOpenHelper {
	private static final String DB_NAME = "movie.db";

	public AppSQLiteOpenHelper(Context context) {
		super(context, DB_NAME, null, ManageApp.getVersionCode(context));
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createTable(db, DbMovie.class);
		createTable(db, DbDrama.class);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// db.execSQL("ALTER TABLE person ADD amount integer NULL");
	}

	private void createTable(SQLiteDatabase db, Class clazz) {
		try {
			Map<String, String> params = new HashMap<String, String>();
			Object newInstance = clazz.newInstance();
			Field[] declaredFields = clazz.getDeclaredFields();
			String sql = "";
			for (int i = 0; i < declaredFields.length; i++) {
				Field field = declaredFields[i];
				DBField annotation = field.getAnnotation(DBField.class);
				if (annotation != null) {
					field.setAccessible(true);
					String key = (String) field.get(newInstance);
					String value = annotation.value();
					params.put(key, value);
				}
			}
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				String value = params.get(key);
				sql += key + " " + value + ",";
			}
			sql = sql.substring(0, sql.length() - 1);
			params = null;

			Field tableFiled = clazz.getDeclaredField("TABLE");
			String table = "";
			if (tableFiled != null) {
				tableFiled.setAccessible(true);
				table = (String) tableFiled.get(newInstance);
			} else {
				throw new RuntimeException("table 不能没有");
			}

			sql = "create table " + table + "(" + sql + ")";
			db.execSQL(sql);
		} catch (Exception e) {
			LogUtils.exception(e);
		}
	}

}
